/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ad.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.shiro.realm.LoginInfo;
import com.jeesite.modules.ad.dao.AdAgentDao;
import com.jeesite.modules.ad.entity.AdAgent;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.dao.UserRoleDao;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.entity.UserRole;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.PwdUtils;
import com.jeesite.modules.sys.utils.UserUtils;

/**
 * 广告代理商Service
 * 
 * @author Liu,Wenzhao
 * @version 2019-04-15
 */
@Service
@Transactional(readOnly = true)
public class AdAgentService extends CrudService<AdAgentDao, AdAgent> {

	@Autowired
	private UserService userService;

	@Autowired
	private UserRoleDao userRoleDao;

	@Autowired
	private AdAgentDao adAgentDao;

	/**
	 * 获取单条数据
	 * 
	 * @param adAgent
	 * @return
	 */
	@Override
	public AdAgent get(AdAgent adAgent) {
		return super.get(adAgent);
	}

	public AdAgent getByAccount(AdAgent a) {
		return this.dao.getByAccount(a);
	}

	public AdAgent getCurAgent() {
		LoginInfo loginInfo = UserUtils.getLoginInfo();
		AdAgent curAgent = this.getByUserCode(loginInfo.getId());
		return curAgent;
	}

	public AdAgent getByUserCode(String userCode) {
		AdAgent a = new AdAgent();
		a.setUserCode(userCode);
		List<AdAgent> list = this.dao.findList(a);
		return ListUtils.isEmpty(list) ? null : list.get(0);
	}

	/**
	 * 查询分页数据
	 * 
	 * @param adAgent 查询条件
	 * @param         adAgent.page 分页对象
	 * @return
	 */
	@Override
	public Page<AdAgent> findPage(AdAgent adAgent) {
		// 如果是代理商,只查询下级
		AdAgent curAgent = this.getCurAgent();
		if (curAgent != null && (StringUtils.isBlank(adAgent.getUpperAgent()) || ",".equals(adAgent.getUpperAgent()))) {
			adAgent.setUpperAgent(curAgent.getId());
		}
		Page<AdAgent> page = super.findPage(adAgent);
		List<AdAgent> list = page.getList();
		if (ListUtils.isNotEmpty(list)) {
			for (AdAgent a : list) {
				if (StringUtils.isEmpty(a.getUpperAgent())) {
					AdAgent pAgent = new AdAgent();
					pAgent.setAccount("系统管理员");
					a.setpAgent(pAgent);
					continue;
				}
				AdAgent p = this.get(a.getUpperAgent());
				a.setpAgent(p);
			}
		}
		return page;
	}

	/**
	 * 保存数据（插入或更新）
	 * 
	 * @param adAgent
	 */
	@Override
	@Transactional(readOnly = false)
	public void save(AdAgent adAgent) {
		if (StringUtils.isBlank(adAgent.getUpperAgent())) {
			LoginInfo loginInfo = UserUtils.getLoginInfo();
			AdAgent curAgent = this.getByUserCode(loginInfo.getId());
			if (curAgent != null && adAgent.getIsNewRecord()) {
				// 新增时设置父级
				adAgent.loadUpperAgent(curAgent);
				this.dao.addAgentNum(curAgent);
			}
		}

		if (adAgent.getIsNewRecord()) {
			adAgent.setUserCode(adAgent.getAccount());
			adAgent.setAgentNum(0l);
			adAgent.setCustomerNum(0l);
			super.save(adAgent);

			User u = new User();
			BeanUtils.copyProperties(adAgent, u);
			u.setSex("1");
			u.setLoginCode(adAgent.getAccount());
			u.setUserName(adAgent.getAccount());
			userService.save(u);

			UserRole ur = new UserRole();
			ur.setRoleCode("dls");
			ur.setUserCode(u.getUserCode());
			this.userRoleDao.insert(ur);
		} else {
			User u = this.userService.get(adAgent.getAccount());
			BeanUtils.copyProperties(adAgent, u);
			u.setPassword(PwdUtils.encryptPassword(u.getPassword()));
			userService.save(u);
			super.save(adAgent);
		}
		// 保存上传附件
		FileUploadUtils.saveFileUpload(adAgent.getId(), "adAgent_license");
		FileUploadUtils.saveFileUpload(adAgent.getId(), "adAgent_icp");
		FileUploadUtils.saveFileUpload(adAgent.getId(), "adAgent_otherLicense");
	}

	/**
	 * 更新状态
	 * 
	 * @param adAgent
	 */
	@Override
	@Transactional(readOnly = false)
	public void updateStatus(AdAgent adAgent) {
		super.updateStatus(adAgent);
		User u = userService.get(this.get(adAgent).getUserCode());
		u.setStatus(adAgent.getStatus());
		userService.updateStatus(u);
	}

	/**
	 * 删除数据
	 * 
	 * @param adAgent
	 */
	@Override
	@Transactional(readOnly = false)
	public void delete(AdAgent adAgent) {
		if (adAgent != null) {
			String id = adAgent.getId();
			if (!StringUtils.isBlank(id)) {
				AdAgent where = new AdAgent();
				where.setUpperAgent(id);
				// 含有下级节点时不能删除
				if (this.findCount(where) > 0) {
					throw newValidationException("该代理商下拥有下级代理商，无法删除");
				} else {
					// 代理商对应用户编码
					String userCode = adAgent.getUserCode();
					// 删除用户
					adAgentDao.deleteUser(userCode);
					// 删除用户对应角色
					adAgentDao.deleteUserAndAuth(userCode);
					super.delete(adAgent);
				}
			}
		}
	}

	@Transactional(readOnly = false)
	public void addCustomerNum(AdAgent adAgent) {
		this.dao.addCustomerNum(adAgent);
	}
}